
# usage : 4 3 c # combination
# usage : 4 3 p # permutation
function math-gen-permutation-or-combination ()
{
    date=`date "+%Y%m%d%H%M%S"`
    tmp_file=/tmp/.$$.$USER.$date
(
cat <<EOF
#!/bin/bash
# permutation_combination
# Version: 4.1
# Author : YongYe <complex.invoke@gmail.com>
# http://bbs.chinaunix.net/thread-3754120-1-1.html

arg0=-1
sep="."
argv=\${3:-p}
number=\${2:-3}
eval ary=({1..\${1:-4}})
length=\${#ary[@]}
((limit=length-number))
(( number > length )) && exit 1

percom(){ loop i \${1} number\${2} \${3} \${4} \${5}; }
invoke(){ echo \$(percom \${argu} loop -1) prtcom \$(percom \${argu}); }
permut(){ echo -n "\${1} arg\${i} \${2} "; (( \${#} != 0 )) && echo -n " length "; }
combin(){ (( \${#} != 0 )) && echo -n "\${1} arg\$((i+1)) arg\${i} limit+\$((i+1)) " || echo -n "arg\$((i+1)) "; }
prtcom(){ num=0; for i in \${@}; do echo -n \${ary[\${!i}]}; (( ++num != number )) && echo -n "\${sep}"; done; echo; }

function loop()
{
   local arc=""
   local arg=""
   arg=\${1//arg}
   for((\${1}=\${2}+1; \${1}<\${3}; ++\${1})); do
        if [[ \${1//[0-9]} == arg ]]; then
              for((arc=1; arc!=arg; ++arc)); do
                   (( \${1} == arg\${arc} )) && continue 2
              done
        fi
        eval eval \\\\$\{{4..\${#}}\}
   done
}

case \${argv} in
     P|p) argu="-0 +1 permut" ;;
     C|c) argu="-1 +0 combin" ;;
     *  ) exit 1              ;;
esac

\$(invoke)
EOF
) > $tmp_file
    bash $tmp_file "$@"
}
